import { Loading } from "element-ui";

const diffTime = new Date(2023, 1, 1);

/**
 * 扣除 2023-1-1 日之前的时间，取结果时间，作为时间戳ID
 * @returns
 */
export function getCacheId() {
  return parseInt(((new Date().getTime() - diffTime.getTime()) / 1000).toFixed(0)).toString(36);
}

/**
 * 显示加载提示
 * @param message
 * @returns
 */
export function showLoading(message: string) {
  return Loading.service({
    fullscreen: true,
    lock: true,
    spinner: "el-icon-loading",
    customClass: "dark",
    text: message,
  });
}

//#region 能提示，不稳定。需要针对网页有交互操作后，才会触发提示
function windowUnload(e) {
  e.preventDefault();
  window.focus();
}
function windowBeforeUnload(e) {
  e.preventDefault();
  window.focus();
  const msg = "当前操作会刷新整个系统缓存，你的操作可能会丢失，是否继续？";
  e.returnValue = msg;
  // navigator.sendBeacon("",{})// 无阻塞发送统计数据。发送诊断数据？
  return msg;
}
/**
 * 启用页面刷新或者关闭时的事件监听提示
 */
export function enableUnloadMessage() {
  window.addEventListener("unload", windowUnload);
  window.addEventListener("beforeunload", windowBeforeUnload);
}
/**
 * 禁用页面刷新或者关闭时的事件监听提示
 */
export function disableUnloadMessage() {
  window.removeEventListener("unload", windowUnload);
  window.removeEventListener("beforeunload", windowBeforeUnload);
}
/**
 * 禁用所有页面刷新或者关闭时的事件监听提示
 */
export function disableAllUnloadMessage() {
  disableUnloadMessage();
  window.onunload = null;
  window.onbeforeunload = null;
}
//#endregion

export function urlCombine(...paths: string[]) {
  let nPath = paths[0];
  paths = paths.slice(1);
  if (paths.length) {
    paths.forEach(item => {
      if (nPath.endsWith("/") && item.startsWith("/")) {
        nPath += item.slice(1);
      } else if (!nPath.endsWith("/") && !item.startsWith("/")) {
        nPath += "/" + item;
      } else {
        nPath += item;
      }
    });
  }
  return new URL(nPath, location.origin);
}

export const CURRENT_BASE_URL = location.origin + location.pathname.split("/").slice(0, -1).join("/");
